package com.woniuxy.repay.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shichen
 * @create 2021-11-17-10:31
 * @description
 */
public class CrossOrignFilter implements Filter {

    private static final Log log = LogFactory.get();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info(">>>>>CrossOrignFilter");
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        String origin = req.getHeader("Origin");
        if (!org.springframework.util.StringUtils.isEmpty(origin)) {
            //带cookie的时候，origin必须是全匹配，不能使用*
            res.addHeader("Access-Control-Allow-Origin", origin);
        }
        res.addHeader("Access-Control-Allow-Methods", "*");
        String headers = req.getHeader("Access-Control-Request-Headers");
        // 支持所有自定义头
        if (!org.springframework.util.StringUtils.isEmpty(headers)) {
            res.addHeader("Access-Control-Allow-Headers", headers);
        }
        res.addHeader("Access-Control-Max-Age", "3600");
        // enable cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("access-control-expose-headers", "*");
        //处理options请求
        if (req.getMethod().toUpperCase().equals("OPTIONS")) {
            log.info(">>>>>CrossOrignFilter---OPTIONS");
//            res.setStatus(HttpStatus.OK.value());
            res.setStatus(HttpStatus.NO_CONTENT.value());
//            return;
        }
        chain.doFilter(request, response);
    }
}
